package com.leo.view;

import com.leo.EmailFxApp;
import com.leo.bean.Customer;
import com.leo.common.ApplicationContentUtil;
import com.leo.common.JFUtils;
import com.leo.db.DaoMapperProxy;
import com.leo.mapper.UserMapper;
import javafx.animation.TranslateTransition;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

/**
 * @author wangss
 */
@Slf4j
public class LoginView extends StackPane {

    // 主界面
    private final StackPane container = new StackPane();
    // 封面
    private final StackPane coverPane = new StackPane();
    private final Button loginBut = new Button("登录");
    // 右侧区域 表单展示
    private final VBox mainContainer = new VBox();

    {
        this.getChildren().add(container);
        //
        container.getChildren().add(mainContainer);
        setAlignment(mainContainer, Pos.CENTER_RIGHT);
        //
        coverPane.getChildren().add(loginBut);
        container.getChildren().add(coverPane);
        container.getStyleClass().add("container");
        mainContainer.getStyleClass().add("main-container");
        coverPane.getStyleClass().add("cover-pane");
        loginBut.getStyleClass().add("login-but");
        this.getStylesheets().add(EmailFxApp.class.getResource("css/login.css").toExternalForm());
        //拖动
        JFUtils.dragCurrentWindow(container);
    }

    private final HBox topBox = new HBox();
    //最小化，关闭窗口按钮
    private final Button hideBut = new Button();
    private final Button closeBut = new Button();

    {
        container.getChildren().addAll(topBox);
        setAlignment(topBox, Pos.TOP_RIGHT);
        topBox.setMaxWidth(0);
        topBox.setMaxHeight(0);
        topBox.getStyleClass().add("top-box");
        topBox.getChildren().addAll(hideBut, closeBut);
        hideBut.setGraphic(new FontIcon(AntDesignIconsOutlined.MINUS));
        closeBut.setGraphic(new FontIcon(AntDesignIconsOutlined.CLOSE));
        hideBut.getStyleClass().add("hide-but");
        closeBut.getStyleClass().add("close-but");
        hideBut.setOnMouseClicked(event -> JFUtils.setIconified(event.getSource(), true));
        closeBut.setOnMouseClicked(event -> JFUtils.closeCurrentWindow(event.getSource()));
    }

    //logo
    private final Pane logo = new Pane();
    //表单内容
    private final Label titleLabel = new Label("你好！欢迎登录");
    private final Label emailLabel = new Label("使用你的邮箱登录");

    {
        mainContainer.getChildren().addAll(logo, titleLabel);
        mainContainer.setAlignment(Pos.CENTER);
        titleLabel.getStyleClass().add("title-label");
        //邮箱登录方式
        emailLabel.getStyleClass().add("email-label");
        mainContainer.getChildren().add(emailLabel);
        //logo
        logo.getStyleClass().add("logo");
    }

    //文本框，密码框
    /**
     * 输入框布局-----------------------------------------------------------
     */
    private final HBox userBox = new HBox();
    private final Label userLabel = new Label();
    private final TextField userField = new TextField();
    //
    private final HBox pswBox = new HBox();
    private final Label pswLabel = new Label();
    private final PasswordField pswField = new PasswordField();
    // 忘记、注册
    private final HBox forgetRegisBox = new HBox();
    private final Button forget = new Button("忘记密码？");
    private final Button regisBut = new Button("注册");
    // 登录
    private final Button login = new Button("登录");
    // 提示语
    private final Label message = new Label();

    {
        mainContainer.getChildren().addAll(userBox, pswBox, forgetRegisBox, login, message);
        //
        userBox.getChildren().addAll(userLabel, userField);
        HBox.setHgrow(userField, Priority.ALWAYS);
        userBox.getStyleClass().add("user-box");
        userLabel.setGraphic(new FontIcon(AntDesignIconsOutlined.MAIL));
        userLabel.getStyleClass().add("user-label");
        userField.setPromptText("邮箱");
        userField.getStyleClass().add("user-field");
        //
        pswBox.getChildren().addAll(pswLabel, pswField);
        HBox.setHgrow(pswField, Priority.ALWAYS);
        pswBox.getStyleClass().add("psw-box");
        pswLabel.setGraphic(new FontIcon(AntDesignIconsOutlined.LOCK));
        pswLabel.getStyleClass().add("psw-label");
        pswField.getStyleClass().add("psw-field");
        pswField.setPromptText("密码");
        // 注册
        forgetRegisBox.getChildren().addAll(forget, regisBut);
        forgetRegisBox.getStyleClass().add("for-reg-box");
        forget.getStyleClass().add("forget");
        regisBut.getStyleClass().add("regis");
        login.getStyleClass().add("login");
        //提示语
        message.getStyleClass().add("message");
    }

    /**
     * 封面的移动动画
     */
    private final TranslateTransition translate1 = new TranslateTransition(Duration.seconds(1), coverPane);
    /**
     * 表单的移动动画
     */
    private final TranslateTransition translate2 = new TranslateTransition(Duration.seconds(1), mainContainer);

    public LoginView() {
        //封面动画
        loginBut.setOnMouseClicked(event -> {
            //设置动画要移动到的位置
            translate1.setFromX(0);
            translate1.setToX(coverPane.getWidth() / 2);
            //
            translate2.setFromX(0);
            translate2.setToX(0 - mainContainer.getWidth());
            //开始动画
            translate1.play();
            translate2.play();
            translate1.setOnFinished(actionEvent -> loginBut.setVisible(false));
        });
        //
        //输入框选中事件绑定
        userField.focusedProperty().addListener((observableValue, aBoolean, t1) -> {
            String color = t1 ? "base-color;" : "rgb(182,182,182);";
            userBox.setStyle(String.format("-fx-border-color:%s", color));
            userLabel.setStyle(String.format("-fx-border-color:%s", color));
            userLabel.getGraphic().setStyle(String.format("-fx-icon-color:%s", color));
        });
        pswField.focusedProperty().addListener((observableValue, aBoolean, t1) -> {
            String color = t1 ? "base-color;" : "rgb(182,182,182);";
            pswBox.setStyle(String.format("-fx-border-color:%s", color));
            pswLabel.setStyle(String.format("-fx-border-color:%s", color));
            pswLabel.getGraphic().setStyle(String.format("-fx-icon-color:%s", color));
        });
        // 忘记密码
        forget.setOnMouseClicked(event -> new ForgetView());
        // 注册
        regisBut.setOnMouseClicked(event -> new RegisView());
        //登录点击事件
        login.setOnMouseClicked(event -> {
            event.consume();
            if (Cursor.WAIT.equals(login.getCursor())) {
                return;
            }
            String email = userField.getText();
            String password = pswField.getText();
            log.info("email:[{}]; password:[{}]", email, password);
            if ("".equals(email.trim())) {
                message.setText("邮箱不能为空");
                return;
            }
            if ("".equals(password.trim())) {
                message.setText("密码不能为空");
                return;
            }
            login.setCursor(Cursor.WAIT);
            try {
                UserMapper userMapper = DaoMapperProxy.getProxyInstance(UserMapper.class);
                Customer customer = userMapper.selectCustomer(email, password);
                log.info("customer = {}", customer);
                if (null == customer) {
                    message.setText("邮箱或者密码错误");
                    login.setCursor(null);
                    return;
                }
                message.setText("登录成功");
                log.info("用户[{}]登录成功", email);
                ApplicationContentUtil.putContentMap("currentUser", email);
                ApplicationContentUtil.putContentMap("userId", customer.getId());
                // 关闭老界面，打开新界面
                Parent fxmlLoader = FXMLLoader.load(EmailFxApp.class.getResource("/com/leo/view/main.fxml"));
                Scene scene = new Scene(fxmlLoader, null);
                Stage stage = new Stage();
                stage.setTitle("邮箱");
                stage.getIcons().add(new Image(EmailFxApp.class.getResource("/com/leo/images/Email.png").toExternalForm()));
                stage.setScene(scene);
                stage.setResizable(false);
                stage.show();
            } catch (Exception e) {
                log.error(e.getMessage());
                login.setCursor(null);
            } finally {
                if (null != ApplicationContentUtil.getContentMapValue("userId")) {
                    Stage primayStage = (Stage) this.getScene().getWindow();
                    primayStage.close();
                }
            }
        });

    }

}
